package com.fqcar.fqdf.ui.chargemap;

import android.os.Bundle;
import android.view.View;

import com.android.volley.Response;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.entity.CarDetailEntity;
import com.fqcar.fqdf.entity.CarDetailRespBean;
import com.fqcar.fqdf.entity.CarInfo;
import com.fqcar.fqdf.entity.CarStubListRespBean;
import com.fqcar.fqdf.entity.StubDetailEntity;
import com.fqcar.fqdf.entity.StubDetailRespBean;
import com.fqcar.fqdf.entity.StubInfo;
import com.fqcar.fqdf.service.RequestOptService;
import com.fqcar.fqdf.ui.MapLocationActivity;
import com.fqcar.fqdf.ui.chargemap.runnable.StubOverlayRunnable;
import com.fqcar.fqdf.ui.chargemap.view.StubViewHelper;
import com.fqcar.fqdf.ui.main.holder.MainHolderHelper;
import com.fqcar.fqdf.ui.main.marker.MainBaiduMarkerHelper;
import com.fqcar.fqdf.ui.main.runnable.BaiduRunnable;
import com.fqcar.fqdf.ui.main.runnable.noui.CarOverlayRunnable;
import com.fqcar.fqdf.util.Constants;
import com.fqcar.fqdf.util.DialogUtil;
import com.fqcar.fqdf.util.NavigationUtils;
import com.fqdf.framework.android.net.response.NetBeanWrapper;
import com.fqdf.framework.android.util.CheckLogicUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 充电桩首页
 */
/*public class StubHomeActivity extends MapLocationActivity implements BaiduMap.OnMapStatusChangeListener,
        BaiduMap.OnMarkerClickListener, OnMapClickListener, OnGetGeoCoderResultListener {

    @BindView(R.id.baidumap)
    MapView baidumapView;

    // 充电界面数据结果
    private CarStubListRespBean carStubListRespBean;
    // 百度地图绘制overlay的帮助类
    private MainBaiduMarkerHelper markerHelper;
    // 控制view显示隐藏以及更新内容的帮助类
    private StubViewHelper stubViewHelper;
    // 用来绘制overlay创建view转化的帮助类
    private MainHolderHelper mainHolderHelper;
    // 用来保存最后一次用户点击的overlay对象
    private Marker lastClickMarker;
    // 当前选择的取车网点的数据对象
    private CarInfo curSelCarEntity;
    private StubInfo curSelStubEntity;
    //当前选取车辆的详情
    private CarDetailEntity carDetailEntity;
    private CarDetailRespBean carDetailRespBean;
    //当前选取充电桩的详情
    private StubDetailEntity stubDetailEntity;
    private StubDetailRespBean stubDetailRespBean;

    //定位
    private BDLocation location = null;
    //逆地理
    private GeoCoder geoCoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stub_home);
        ButterKnife.bind(this);
        //初始化数据
        initData();
        // 调用父类的地图初始化
        initMap(baidumapView);
        // 初始化本地地图的个性设置
        initMyMap();
        // 初始化各个帮助类
        initHelper();
        // 初始化请求数据
        initReqData();
    }

    // 初始化地图设置
    private void initMyMap() {
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapStatusChangeListener(this);
        mBaiduMap.setOnMapClickListener(this);

    }

    // 初始化帮助类
    private void initHelper() {
        mainHolderHelper = new MainHolderHelper(this);
        markerHelper = new MainBaiduMarkerHelper(this, mBaiduMap, mainHolderHelper);
        stubViewHelper = new StubViewHelper(this, getWindow().findViewById(android.R.id.content));
        stubViewHelper.setTitle(getResources().getString(R.string.title_charge_home));
    }

    private void initData() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(this);

    }

    *//**
     * 初始化请求数据
     *//*
    private void initReqData() {
        // 开始进行定位
        startLocationUpdate();

        // 根据定位获取网点数据以及更新对应的城市代码。如果定位数据为空，则进行1秒等待后继续调用
        getThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                if (getCurValidAndCityLocation() != null) {
                    location = getCurValidAndCityLocation();
//                    Log.d("区县信息：",location.getDistrict());
                    updateData();
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(new LatLng(location.getLatitude(), location.getLongitude()))
                            .zoom(MAP_ZOOM_DEFAULT)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.animateMapStatus(mMapStatusUpdate);

                } else {
                    startLocationUpdate();
                    getThreadHandler().postDelayed(this, 1000);
                }
            }
        });
    }

    @OnClick({R.id.main_back_iv,R.id.main_function_location, R.id.nav_btn, R.id.stub_nav_btn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_back_iv:
                finish();
                break;
            case R.id.main_function_location:
                BDLocation curLocation = getCurValidAndCityLocation();
                // 定位当前位置，如果当前位置有效的话地图移动到我的定位
                if (curLocation != null) {
                    changePosition(curLocation.getLatitude(), curLocation.getLongitude());
                }
                break;
            case R.id.nav_btn:
                NavigationUtils.showNavigationDialog(StubHomeActivity.this, new LatLng(curSelCarEntity.getLat(), curSelCarEntity.getLng()),
                        NavigationUtils.Driving, NavigationUtils.ReturnCar, "车辆位置");
                break;
            case R.id.stub_nav_btn:
                NavigationUtils.showNavigationDialog(StubHomeActivity.this, new LatLng(curSelStubEntity.getLat(), curSelStubEntity.getLng()),
                        NavigationUtils.Driving, NavigationUtils.ReturnCar, stubDetailEntity.getTitle());
                break;
            default:
                break;
        }
    }

    *//**
     *
     *//*
    private void clearClickInfo() {
        if (curSelCarEntity != null) {
            curSelCarEntity.setSelect(false);
        }
        if (curSelStubEntity != null) {
            curSelStubEntity.setSelect(false);
        }
//        if (lastWalkingRouteOverlay != null) {
//            lastWalkingRouteOverlay.removeFromMap();
//        }
        curSelCarEntity = null;
        curSelStubEntity = null;
        lastClickMarker = null;
//        curSelReturnParkingEntity = null;

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        if (lastClickMarker == marker || marker.getExtraInfo() == null) {
            return false;
        }
        Bundle bundle = marker.getExtraInfo();
        if (bundle.containsKey(Constants.BUNDLE_CARENTITY)) {//车

            Marker changeMarker = updateCarMarker(marker);
            lastClickMarker = changeMarker;
            CarInfo bundleItem = changeMarker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);

            CarInfo originItem = getOriginCarEntity(bundleItem.getCarId());

            curSelCarEntity = originItem;

            getCarDetailInfo(curSelCarEntity.getCarId(), location.getLatitude(), location.getLongitude());

        } else if (bundle.containsKey(Constants.BUNDLE_STUB_ENTITY)) {//充电桩

            Marker changeMarker = updateStubMarker(marker);
            lastClickMarker = changeMarker;
            StubInfo bundleItem = changeMarker.getExtraInfo().getParcelable(Constants.BUNDLE_STUB_ENTITY);

            StubInfo originItem = getOriginStubEntity(bundleItem.getStubId());

            curSelStubEntity = originItem;

            getStubDetailInfo(curSelStubEntity.getStubId(),location.getLatitude(), location.getLongitude());
        }

        return true;
    }

    *//**
     * 更新车辆marker状态
     *
     * @param marker
     * @return
     *//*
    private Marker updateCarMarker(Marker marker) {
        // 如果上次点中的marker存在，则修改上次点中的marker状态。
        if (null != lastClickMarker) {
            lastClickMarker.remove();

            if (lastClickMarker.getExtraInfo().containsKey(Constants.BUNDLE_CARENTITY)) {
                CarInfo lastClickCarInfo = lastClickMarker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);
                lastClickCarInfo.setSelect(false);
                markerHelper.createCarMarker(lastClickCarInfo);
            } else if (lastClickMarker.getExtraInfo().containsKey(Constants.BUNDLE_STUB_ENTITY)) {
                StubInfo lastClickCarInfo = lastClickMarker.getExtraInfo().getParcelable(Constants.BUNDLE_STUB_ENTITY);
                lastClickCarInfo.setSelect(false);
                markerHelper.createStubMarker(lastClickCarInfo);
            }
        }

        // 更改当前点中的marker状态
        CarInfo curItem = marker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);
        marker.remove();
        curItem.setSelect(true);

        Marker changeMarker = (Marker) markerHelper.createCarMarker(curItem);
        return changeMarker;
    }

    *//**
     * 更新充电桩marker状态
     *
     * @param marker
     * @return
     *//*
    private Marker updateStubMarker(Marker marker) {
        // 如果上次点中的marker存在，则修改上次点中的marker状态。
        if (null != lastClickMarker) {
            lastClickMarker.remove();
            if (lastClickMarker.getExtraInfo().containsKey(Constants.BUNDLE_CARENTITY)) {
                CarInfo lastClickCarInfo = lastClickMarker.getExtraInfo().getParcelable(Constants.BUNDLE_CARENTITY);
                lastClickCarInfo.setSelect(false);
                markerHelper.createCarMarker(lastClickCarInfo);
            } else if (lastClickMarker.getExtraInfo().containsKey(Constants.BUNDLE_STUB_ENTITY)) {
                StubInfo lastClickCarInfo = lastClickMarker.getExtraInfo().getParcelable(Constants.BUNDLE_STUB_ENTITY);
                lastClickCarInfo.setSelect(false);
                markerHelper.createStubMarker(lastClickCarInfo);
            }
        }

        // 更改当前点中的marker状态
        StubInfo curItem = marker.getExtraInfo().getParcelable(Constants.BUNDLE_STUB_ENTITY);
        marker.remove();
        curItem.setSelect(true);

        Marker changeMarker = (Marker) markerHelper.createStubMarker(curItem);
        return changeMarker;
    }

    *//**
     * 封装请求数据
     *//*
    private void updateData() {
        getChargeList(location.getLatitude(), location.getLongitude());
    }

    private void getChargeList(double lat, double lng) {
        RequestOptService.getChargeList(this, lat, lng, new Response.Listener<NetBeanWrapper<CarStubListRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<CarStubListRespBean> response) {
                if (handleBeanResponse(response)) {
                    return;
                }
                carStubListRespBean = response.getModelData();
                if (CheckLogicUtil.isEmpty(carStubListRespBean.getCarList())
                        || carStubListRespBean.getCarList().size() <= 0) {
                    DialogUtil.ToastMessage(StubHomeActivity.this,getResources().getString(R.string.charge_home_no_car));
                }
                if (CheckLogicUtil.isEmpty(carStubListRespBean.getChargeList())
                        || carStubListRespBean.getChargeList().size() <= 0) {
                    DialogUtil.ToastMessage(StubHomeActivity.this,getResources().getString(R.string.charge_home_no_stub));
                }
                *//*if(CheckLogicUtil.isEmpty(carStubListRespBean.getCarList())
                        || carStubListRespBean.getCarList().size() <= 0 &&
                        CheckLogicUtil.isEmpty(carStubListRespBean.getChargeList())
                        || carStubListRespBean.getChargeList().size() <= 0){
                    return;
                }*//*
                handlerOverlayList();

            }
        }, getDefaultErrorListener());

    }

    *//**
     * 获取车辆详情
     * @param carId
     * @param lat
     * @param lng
     *//*
    private void getCarDetailInfo(int carId, double lat, double lng) {
        RequestOptService.getCarDetailInfo(this, carId, lat, lng, new Response.Listener<NetBeanWrapper<CarDetailRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<CarDetailRespBean> response) {
                if (handleBeanResponse(response)) {
                    return;
                }
                carDetailRespBean = response.getModelData();
                carDetailEntity = carDetailRespBean.getCarVo();
                LatLng latLng = new LatLng(carDetailEntity.getLat(), carDetailEntity.getLng());
                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption().location(latLng);
                geoCoder.reverseGeoCode(reverseGeoCodeOption);
                updateCarDetailView(carDetailEntity);
            }
        }, getDefaultErrorListener());
    }

    *//**
     * 获取充电桩详情
     * @param stubId
     *//*
    private void getStubDetailInfo(int stubId,double lat, double lng){
        RequestOptService.getChargeDetail(this, stubId,lat,lng, new Response.Listener<NetBeanWrapper<StubDetailRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<StubDetailRespBean> response) {
                if (handleBeanResponse(response)) {
                    return;
                }
                stubDetailRespBean = response.getModelData();
                stubDetailEntity = stubDetailRespBean.getChargeDetail();
//                LatLng latLng = new LatLng(stubDetailEntity.getLat(), stubDetailEntity.getLng());
//                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption().location(latLng);
//                geoCoder.reverseGeoCode(reverseGeoCodeOption);
                updateStubDetailView(stubDetailEntity);

            }
        },getDefaultErrorListener());
    }

    *//**
     * 更新充电桩详情 view
     * @param stubDetailEntity
     *//*
    private void updateStubDetailView(StubDetailEntity stubDetailEntity){

        if(stubDetailEntity != null){
            stubViewHelper.showStubView();
            stubViewHelper.hidenSelCarView();
            stubViewHelper.updateStubAddress(stubDetailEntity.getAddress());
            stubViewHelper.updateStubDistance(stubDetailEntity.getDistance());
            stubViewHelper.updateStubName(stubDetailEntity.getTitle());
            stubViewHelper.updateStubState(stubDetailEntity.getStateDesc());
        }else {
            stubViewHelper.hidenSelCarView();
            stubViewHelper.hiddenStubView();
        }
    }
    
    *//**
     * 更新车辆详情view
     *
     * @param carDetailEntity
     *//*
    private void updateCarDetailView(CarDetailEntity carDetailEntity) {
        if (carDetailEntity != null) {
            stubViewHelper.showSelCarView();
            stubViewHelper.hiddenStubView();
            stubViewHelper.hiddenArrowIcon();
            stubViewHelper.showCarNavBtn();
            stubViewHelper.updateCarPlateNum(carDetailEntity.getLicense());
            stubViewHelper.updateCarBrand(carDetailEntity.getBrand());
            stubViewHelper.updateCarState(carDetailEntity.getOnListingDesc());
            stubViewHelper.updateCarMileage(carDetailEntity.getMileageNumberDesc());
            stubViewHelper.updateCarBattery(carDetailEntity.getSocNumberDesc());
            stubViewHelper.updateCarCharingState(carDetailEntity.getIsChargingDesc());
            stubViewHelper.updateMachineState(carDetailEntity.getStateOnlineDesc());
            stubViewHelper.updateDistance(carDetailEntity.getDistanceDesc());
            if (carDetailEntity.getLastDeal() != null) {
                *//*if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getEndTime())) {
                    stubViewHelper.updateCarStateDescTime(carDetailEntity.getLastDeal().getEndTime(),R.color.black);
                } else {
                    stubViewHelper.updateCarStateDescTime(getString(R.string.manage_doing_txt),R.color.nf26050);
                }*//*
                stubViewHelper.updateCarStateDescTime(carDetailEntity.getLastDeal().getEndTimeDesc());
                stubViewHelper.updateOperation(carDetailEntity.getLastDeal().getManagerName());
                if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause()) && !CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    stubViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getCause() + "," + carDetailEntity.getLastDeal().getDetail());
                } else if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    stubViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getDetail());
                } else if (!CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause())) {
                    stubViewHelper.updateCarStateDesc(carDetailEntity.getLastDeal().getCause());
                } else if (CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getCause()) && CheckLogicUtil.isEmpty(carDetailEntity.getLastDeal().getDetail())) {
                    stubViewHelper.updateCarStateDesc("");
                }
            } else {
                stubViewHelper.updateCarStateDescTime(Constants.BLANK);
                stubViewHelper.updateCarStateDesc(Constants.BLANK);
                stubViewHelper.updateOperation(Constants.BLANK);
            }
        }else {
            stubViewHelper.hidenSelCarView();
            stubViewHelper.hiddenStubView();
        }
    }

    *//**
     * 处理数据
     *//*
    private void handlerOverlayList() {
        clearOverlay();
        setOpenUserLocation(true);
        addOverlayList(carStubListRespBean);
    }

    *//**
     * 获取原始的网点对象 由于parcel不是引用的对象，实际上相当于克隆，所以容易造成不同步的问题
     *
     * @return
     *//*
    private CarInfo getOriginCarEntity(int carId) {
        if (carStubListRespBean != null && !CheckLogicUtil.isEmpty(carStubListRespBean.getCarList())) {
            CarInfo item = getCarEntity(carStubListRespBean.getCarList(), carId);
            return item;
        }
        return null;
    }

    *//**
     * @param stubId
     * @return
     *//*
    private StubInfo getOriginStubEntity(int stubId) {
        if (carStubListRespBean != null && !CheckLogicUtil.isEmpty(carStubListRespBean.getChargeList())) {
            StubInfo item = getStubEntity(carStubListRespBean.getChargeList(), stubId);
            return item;
        }
        return null;
    }

    *//**
     * 更新网点的数据
     *
     * @param carId
     * @param select
     *//*
    *//*private void updateOriginParkingEntity(int carId, boolean select) {
        CarInfo item = getOriginCarEntity(carId);
        if (item != null) {
            item.setSelect(select);
        }
    }*//*

    *//**
     * 从网点实体取得当前carId对应的实体
     *
     * @param carInfoList
     * @param carId
     * @return
     *//*
    private CarInfo getCarEntity(List<CarInfo> carInfoList, int carId) {
        if (CheckLogicUtil.isEmpty(carInfoList)) {
            return null;
        }
        for (CarInfo carInfo : carInfoList) {
            if (carInfo.getCarId() == carId) {
                return carInfo;
            }
        }
        return null;
    }

    *//**
     * 获取stub实体
     * @param stubInfoList
     * @param stubId
     * @return
     *//*
    private StubInfo getStubEntity(List<StubInfo> stubInfoList, int stubId) {
        if (CheckLogicUtil.isEmpty(stubInfoList)) {
            return null;
        }
        for (StubInfo stubInfo : stubInfoList) {
            if (stubInfo.getStubId() == stubId) {
                return stubInfo;
            }
        }

        return null;
    }

    *//**
     * 增加overlay到地图上
     *//*
    private void addOverlayList(CarStubListRespBean carStubListRespBean) {

        if (carStubListRespBean == null) {
            return;
        }

        BaiduRunnable addOverlayRunnable;//car列表
        BaiduRunnable addOverlayStubRunnable;//充电桩列表

        addOverlayRunnable = new CarOverlayRunnable(stubViewHelper, getBaiduMap(), carStubListRespBean.getCarList(), markerHelper, new BaiduRunnable.MyRunnableListener() {
            @Override
            public void handleFinish(List<Overlay> dataList) {

                if (!CheckLogicUtil.isEmpty(dataList)) {
                    //  对于已经被选中的view 设置最后被点击的view
                    for (Overlay item : dataList) {
                        if (item.getExtraInfo().getBoolean(Constants.BUNDLE_DATA, false)) {
                            lastClickMarker = (Marker) item;
                        }
                    }
                }
            }
        });
        addOverlayStubRunnable = new StubOverlayRunnable(stubViewHelper, getBaiduMap(), carStubListRespBean.getChargeList(), markerHelper, new BaiduRunnable.MyRunnableListener() {
            @Override
            public void handleFinish(List<Overlay> dataList) {

                if (!CheckLogicUtil.isEmpty(dataList)) {
                    //  对于已经被选中的view 设置最后被点击的view
                    for (Overlay item : dataList) {
                        if (item.getExtraInfo().getBoolean(Constants.BUNDLE_DATA, false)) {
                            lastClickMarker = (Marker) item;
                        }
                    }
                }
            }
        });

        getThreadHandler().post(addOverlayStubRunnable);
        getThreadHandler().postDelayed(addOverlayRunnable, 100);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        // 设置当前的网点作为选中网点
        stubViewHelper.hidenSelCarView();
        stubViewHelper.hiddenStubView();

        if (curSelCarEntity != null) {

            if (lastClickMarker != null) {
                lastClickMarker.remove();
            }

            curSelCarEntity.setSelect(false);
            markerHelper.createCarMarker(curSelCarEntity);
        }
        if (curSelStubEntity != null) {
            if (lastClickMarker != null) {
                lastClickMarker.remove();
            }

            curSelStubEntity.setSelect(false);
            markerHelper.createStubMarker(curSelStubEntity);
        }
        curSelCarEntity = null;
        curSelStubEntity = null;
        lastClickMarker = null;
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }


    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        }
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        } else {
            stubViewHelper.updateCarAddress(reverseGeoCodeResult.getAddress());
        }
    }

}*/
